package com.lanou.bookstore.user.dao;

import com.lanou.bookstore.user.domain.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    // c3p0初始化
    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

    @Override
    public List<User> findByUsername(User user) {

        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            List<User> slist = qr.query(conn, "select * from tb_user where username = ?", user.getUsername(),new BeanListHandler<User>(User.class));

            DbUtils.close(conn);
            return slist;

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;

    }

    @Override
    public List<User> findByEmail(User user) {

        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            List<User> slist = qr.query(conn, "select * from tb_user where email = ?", user.getEmail(),new BeanListHandler<User>(User.class));

            DbUtils.close(conn);
            return slist;

        } catch (SQLException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public int add(User user) {

        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            int result = qr.update(conn, "insert into tb_user (uid,username,password,email,code) values(?,?,?,?,?)"
                    , user.getUid(), user.getUsername(), user.getPassword(), user.getEmail(), user.getCode());
            DbUtils.close(conn);

            return result;

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return -666;

    }

    @Override
    public List<User> query(User user) {

        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            List<User> slist = qr.query(conn,
                    "select * from tb_user where username = ? and password =?",
                    new BeanListHandler<User>(User.class),
                    user.getUsername(),user.getPassword());

            DbUtils.close(conn);
            return slist;

        } catch (SQLException e) {
            e.printStackTrace();
        }


        return null;

    }
}
